package br.edu.univas.si.es.correios.view;

import java.awt.Color;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.BorderFactory;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class RegexTextField extends JTextField implements DocumentListener { //Componente que se Auto-Valida
	private static final long serialVersionUID = -9052970480384140496L;
	
	private String regex;
	private Boolean hasErrors = true;
	private Color cRight = Color.GREEN;
	private Color cWrong = Color.RED;

	public RegexTextField() {
		this.getDocument().addDocumentListener(this);
	}
	
	RegexTextField(String pattern) {
		regex = pattern;
		this.getDocument().addDocumentListener(this);
	}
	
	RegexTextField(String pattern, Color cRight, Color cWrong ) {
		regex = pattern;
		this.cRight = cRight;
		this.cWrong = cWrong;
		this.getDocument().addDocumentListener(this);
	}

	public Boolean validate(String str) {
		String pRegex = regex;
		Pattern pattern = Pattern.compile(pRegex);
		Matcher matcher = pattern.matcher(str);
		if (matcher.matches())
			return true;
		else
			return false;
	}

	public void cepCheck() {
		if (this.validate(this.getText()))
			setHasErrors(false);
		else
			setHasErrors(true);
	}

	@Override
	public void changedUpdate(DocumentEvent e) {
		cepCheck();
	}

	@Override
	public void insertUpdate(DocumentEvent e) {
		cepCheck();
	}

	@Override
	public void removeUpdate(DocumentEvent e) {
		cepCheck();
	}

	public String getRegex() {
		return regex;
	}

	public void setRegex(String regex) {
		this.regex = regex;
	}

	public Color getcRight() {
		return cRight;
	}

	public void setcRight(Color cRight) {
		this.cRight = cRight;
	}

	public Color getcWrong() {
		return cWrong;
	}

	public void setcWrong(Color cWrong) {
		this.cWrong = cWrong;
	}
	
	public Boolean hasErrors() {
		return hasErrors;
	}
	
	public void setHasErrors(boolean hasErrors) {
		this.hasErrors = hasErrors;
		if(hasErrors){
			Border border = BorderFactory.createLineBorder(cWrong) ;
			this.setBorder(border);
		}
		else{
			Border border = BorderFactory.createLineBorder(cRight) ;
			this.setBorder(border);
		}	
	}

}